import React, { useState, useEffect } from "react";
import { Upload, Modal } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import "antd/lib/upload/style/index.less";
import { OSSConfig, OSSigna } from "@/utils/ossUpload";
export interface FormUploadProps {
	value?: any[];
	limit?: number;
	form?: any;
	name?: string;
	onChange?: (values: any[]) => void;
	[key: string]: any;
}

const FormUpload: React.FC<FormUploadProps> = (props) => {
	const {
		initFileList,
		form,
		name,
		limit = Infinity,
		onChange,
		value,
		...otherProps
	} = props;
	const [previewVisible, setPreviewVisible] = useState<boolean>(false);
	const [previewImage, setPreviewImage] = useState<string>("");
	const [previewTitle, setPreviewTitle] = useState<string>("");
	const [fileList, setFileList] = useState(value || []);

	const uploadProps: any = {
		name: "file",
		fileList,
		listType: "picture-card",
		action: OSSConfig.OSS_HOST,
		data: {
			key: OSSConfig.OSS_TODAY_KEY + "/${filename}",
			policy: OSSConfig.policyBase64,
			OSSAccessKeyId: OSSConfig.OSS_ACCESS_KEY_ID,
			success_action_status: 200,
			signature: OSSigna.signature,
		},
		onChange: ({ file, fileList }: any) => {
			fileList = fileList.map((fe: any) => {
				if (fe.xhr && fe.xhr.status === 200) {
					const response = `${OSSConfig.OSS_HOST}/${OSSConfig.OSS_TODAY_KEY}/${fe.name}`;
					fe.url = response;
				}
				return fe;
			});
			setFileList(fileList);
			// !isUnMounted && setFiles(fileList);
			if (["done", "removed"].includes(file.status)) {
				onChange?.(fileList);
			}
		},
		onPreview: async (file: any) => {
			if (!file.url && !file.preview) {
				const preview = await new Promise((resolve, reject) => {
					const reader = new FileReader();
					reader.readAsDataURL(file.originFileObj);
					reader.onload = () => resolve(reader.result);
					reader.onerror = (error) => reject(error);
				});
				if (typeof preview === "string") {
					file.preview = preview;
				}
			}

			setPreviewImage(file.url || file.preview);
			setPreviewVisible(true);
			setPreviewTitle(
				file.name || file.url.substring(file.url.lastIndexOf("/") + 1)
			);
		},
		...otherProps,
	};

	useEffect(() => {
		setFileList(value || []);
		form?.setFieldsValue({
			[name]: value?.map((m: any) => m.url).join(","),
		});
	}, [value]);

	const uploadButton = (
		<div>
			<PlusOutlined />
			<div className="ant-upload-text">上传</div>
		</div>
	);
	return (
		<div className="clearfix">
			<Upload {...uploadProps}>
				{fileList.length >= limit ? null : uploadButton}
			</Upload>
			<Modal
				visible={previewVisible}
				title={previewTitle}
				footer={null}
				onCancel={() => setPreviewVisible(false)}
			>
				<img style={{ width: "100%" }} src={previewImage} />
			</Modal>
		</div>
	);
};

export default FormUpload;
